<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :destroy-on-close="true"
      :width="!props.isReadonly ? '1100px' : '1100px'"
      :align-center="true"
      draggable
      @close="closeDialog"
      style="min-width: 1100px"
      class="maxhDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120"
        v-show="!props.isReadonly"
        style="width: 99%"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="作业编号" prop="standardCode">
              <el-input
                v-model="formData.standardCode"
                placeholder="请输入作业编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="作业名称" prop="standardName">
              <el-input
                v-model="formData.standardName"
                placeholder="请输入作业名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="作业类型" prop="sopTypeId">
              <el-select
                v-model="formData.sopTypeId"
                placeholder="请选择作业类型"
                clearable
                :disabled="isBind || hasSopType"
                style="width: 100%"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.id"
                  :label="item.sopTypeName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="作业人员类型" prop="standardPersonnel">
              <el-select
                style="width: 100%"
                v-model="formData.standardPersonnel"
                placeholder="请选择作业人员类别"
                clearable
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList(
                    'StandardPersonnel'
                  )"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="工序" prop="processId">
              <el-select
                style="width: 100%"
                v-model="formData.processId"
                placeholder="请选择工序"
                clearable
                :disabled="isBind"
              >
                <el-option
                  v-for="item in processList"
                  :key="item.id"
                  :label="item.processName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品" prop="productId">
              <el-select
                style="width: 100%"
                v-model="formData.productId"
                placeholder="请选择产品"
                clearable
                filterable
                :filter-method="productFilter"
                :disabled="isBind"
              >
                <el-option
                  v-for="item in productFilteredOptions"
                  :key="item.id"
                  :label="item.materialName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="编制时间" prop="standardCompileTime">
              <el-date-picker
                v-model="formData.standardCompileTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请输入编制时间"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="编制人" prop="standardCompilePersonnel">
              <el-input
                v-model="formData.standardCompilePersonnel"
                placeholder="请输入编制人"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核时间" prop="standardExamineTime">
              <el-date-picker
                v-model="formData.standardExamineTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请输入审核时间"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核人" prop="standardExaminePersonnel">
              <el-input
                v-model="formData.standardExaminePersonnel"
                placeholder="请输入审核人"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批准时间" prop="standardRatifyTime">
              <el-date-picker
                v-model="formData.standardRatifyTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请输入批准时间"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批准人" prop="standardRatifyPersonnel">
              <el-input
                v-model="formData.standardRatifyPersonnel"
                placeholder="请输入批准人"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否启用" prop="enabled">
              <el-radio-group v-model="formData.enabled" :disabled="isBind">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="remarks">
              <el-input
                type="textarea"
                v-model="formData.remarks"
                placeholder="请输入备注"
                show-word-limit
                :maxlength="250"
                :autosize="{ minRows: 2, maxRows: 3 }"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-tabs type="border-card">
          <el-tab-pane label="作业指导书">
            <CommonUploadFile
              :isRead="props.isReadonly"
              :files="formData.images"
              @update-files="updateFormFiles"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <el-descriptions
        v-show="props.isReadonly"
        title=""
        :column="3"
        size="large"
        border
        style="width: 99%; max-height: 70vh; overflow-y: auto"
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">作业编号</div>
          </template>
          {{ formData.standardCode || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">作业名称</div>
          </template>
          {{ formData.standardName || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">作业类型</div>
          </template>
          {{ formData.sopTypeName || "" }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">作业人员类型</div>
          </template>
          {{
            dictionaryStore.filterDictName(
              "StandardPersonnel",
              formData.standardPersonnel
            )
          }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">工序</div>
          </template>
          {{ formData.processName || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">产品</div>
          </template>
          {{ formData.productName || "" }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">编制时间</div>
          </template>
          {{ formData.standardCompileTime || "" }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">编制人</div>
          </template>
          {{ formData.standardCompilePersonnel || "" }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">审核时间</div>
          </template>
          {{ formData.standardExamineTime || "" }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">审核人</div>
          </template>
          {{ formData.standardExaminePersonnel || "" }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">批准时间</div>
          </template>
          {{ formData.standardRatifyTime || "" }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">批准人</div>
          </template>
          {{ formData.standardRatifyPersonnel || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">是否启用</div>
          </template>
          <el-tag v-show="formData.enabled === 1" type="">启用</el-tag>
          <el-tag v-show="formData.enabled !== 1" type="info">停用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item :span="3">
          <template #label>
            <div class="cell-item">备注</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "暂无备注" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item :span="3">
          <template #label>
            <div class="cell-item">作业指导书</div>
          </template>
          <div v-if="formData.images && formData.images.length">
            <CommonUploadFile
              :showText="false"
              :isRead="props.isReadonly"
              :files="formData.images"
              @update-files="updateFormFiles"
            />
          </div>
          <div v-else>无</div>
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import {
  getStandardTypesApi,
  getStandardDevicesApi,
  getMakerListApi,
  getBrandModelListApi,
} from "@/utils/commonData";
import { validateNumber } from "@/utils/commonHooks";
import _ from "lodash-es";

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QmsStandardEdit",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const isBind = ref(false);
const hasSopType = ref(false);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  sopType: {
    type: String,
    default: "",
  },
});

const visibleDialog = ref(false);
const formRef = ref(ElForm);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive(<any>{
  remarks: [
    { message: "请输入备注", trigger: "blur" },
    { max: 255, message: "不能超过255个字符", trigger: "blur" },
  ],
  enabled: [{ required: true, message: "请选择是否启用", trigger: "change" }],
  standardCode: [
    { required: true, message: "请输入作业编号", trigger: "blur" },
    { max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  standardName: [
    { required: true, message: "请输入作业名称", trigger: "blur" },
    { min: 1, max: 50, message: "不能超过50个字符", trigger: "blur" },
  ],
  sopTypeId: [{ required: true, message: "请选择作业类型", trigger: "change" }],
  standardPersonnel: [
    { required: true, message: "请选择作业人员类型", trigger: "change" },
  ],
  productId: [{ required: true, message: "请选择产品", trigger: "change" }],
  standardCompilePersonnel: [
    { min: 1, max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  standardExaminePersonnel: [
    { min: 1, max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  standardRatifyPersonnel: [
    { min: 1, max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
});

let formData = reactive({
  id: "",
  version: "",
  remarks: "",
  standardCode: "",
  standardName: "",
  sopTypeId: "",
  equipTypeId: "",

  standardPersonnel: "",
  standardCompileTime: "",
  standardCompilePersonnel: "",
  standardExamineTime: "",
  standardExaminePersonnel: "",
  standardRatifyTime: "",
  standardRatifyPersonnel: "",
  productId: "",
  productCode: "",
  productName: "",
  processId: "",
  processCode: "",
  processName: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  images: [],
  sopTypeName: "",
  assetTypeName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        remarks,
        standardCode,
        standardName,
        bind,
        sopTypeId,
        equipTypeId,
        standardPersonnel,
        standardCompileTime,
        standardCompilePersonnel,
        standardExamineTime,
        standardExaminePersonnel,
        standardRatifyTime,
        standardRatifyPersonnel,
        productId,
        productCode,
        productName,
        processId,
        processCode,
        processName,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        images,
        sopTypeName,
        assetTypeName,
      } = newVal;
      isBind.value = bind;
      Object.assign(formData, {
        id,
        version,
        remarks,
        standardCode,
        standardName,
        sopTypeId,
        equipTypeId,
        standardPersonnel,
        standardCompileTime,
        standardCompilePersonnel,
        standardExamineTime,
        standardExaminePersonnel,
        standardRatifyTime,
        standardRatifyPersonnel,
        productId,
        productCode,
        productName,
        processId,
        processCode,
        processName,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        images: images ?? [],
        sopTypeName,
        assetTypeName,
      });
    } else {
      formData.images = [];
      formData.enabled = 1;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.remarks = "";
  formData.standardCode = "";
  formData.standardName = "";
  formData.sopTypeId = "";
  formData.equipTypeId = "";
  formData.standardPersonnel = "";
  formData.standardCompileTime = "";
  formData.standardCompilePersonnel = "";
  formData.standardExamineTime = "";
  formData.standardExaminePersonnel = "";
  formData.standardRatifyTime = "";
  formData.standardRatifyPersonnel = "";
  formData.productId = "";
  formData.productCode = "";
  formData.productName = "";
  formData.processId = "";
  formData.processCode = "";
  formData.processName = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.sopTypeName = "";
  formData.assetTypeName = "";
  isBind.value = false;
}

const loading = ref(false);

/** 标准作业规程保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const process = processList.value.find(
        (item: any) => item.id === formData.processId
      );
      const product = productList.value.find(
        (item: any) => item.id === formData.productId
      );
      formData.processCode = process?.processCode ?? "";
      formData.processName = process?.processName ?? "";
      formData.productCode = product?.materialCode ?? "";
      formData.productName = product?.materialName ?? "";
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/qmssopstandard/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 获取作业类型列表
const typeList = ref(<any>[]);
async function getTypeList(value: string) {
  const params = {
    taskKind: value,
  };
  const { data } = await request({
    url: "/qms/qmssoptype/getlist",
    method: "post",
    data: params,
  });
  typeList.value = data ?? [];
}

// 图片处理
function updateFormFiles(val: []) {
  formData.images = val;
}

const processList = ref(<any>[]);
const getProcessList = async () => {
  const { data } = await request({
    url: "/mes/mesprocess/getlist",
    method: "post",
    data: {},
  });
  processList.value = data ?? [];
};
const productList = ref(<any>[]);
const getProductList = async () => {
  const { data } = await request({
    url: "/mdm/mdmmaterial/getlist",
    method: "post",
    data: {},
  });
  productList.value = data ?? [];
  productFilteredOptions.value = data;
};

const productFilteredOptions = ref<any>([]);

// 使用 debounce 包装过滤方法
const productFilter = _.debounce((query: any) => {
  if (!query) {
    productFilteredOptions.value = [...productList.value];
    return;
  }
  productFilteredOptions.value = productList.value.filter((option: any) =>
    option.materialName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);

onMounted(async () => {
  await getTypeList("");
  if (props.sopType !== "" && typeList.value.length > 0) {
    formData.sopTypeId = typeList.value.find(
      (item: any) => item.sopTypeCode === props.sopType
    )?.id;
    hasSopType.value = true;
  }
  await getProcessList();
  await getProductList();
});
</script>

<style scoped lang="scss">
:deep(.maxhDialog .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}
.el-form-item {
  margin-bottom: 15px;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
